<template>
    <!-- 二级页导航 -->
    <div class="header-container full-screen-container">
        <div class="main-container flex-between">
            <div class="left-wrap flex-start">
                <div class="flex-start pointer" @click="goSelfUrl('home.home')">
                    <img
                        class="logo"
                        :src="brandInfo?.otherNavLogoUrl || config.defaultLogo"
                        alt="logo"
                    />
                    <div
                        class="site-name"
                        :title="brandInfo?.siteName"
                        :class="{
                            'little-site-name': brandInfo?.siteName?.length > 7
                        }"
                    >
                        {{ brandInfo?.siteName }}
                    </div>
                </div>
                <div class="menu-container flex-between">
                    <ul class="menu-list flex-start" v-show="navList?.length">
                        <li
                            v-for="menuItem in navList || []"
                            class="menu-item flex-start"
                            :class="[
                                'pointer',
                                {active: activeId && activeId === menuItem.id}
                            ]"
                            :key="menuItem?.id"
                            :title="menuItem?.title"
                            @click="changeMenu(menuItem)"
                        >
                            <div
                                class="menu-item-name"
                                :title="menuItem?.title"
                                :class="[
                                    {
                                        'menu-item-snv':
                                            menuItem?.sub_navs?.length
                                    }
                                ]"
                            >
                                {{ menuItem?.title }}
                            </div>
                            <ul
                                class="submenu-list pop-menu-list"
                                v-if="menuItem?.sub_navs?.length"
                            >
                                <li
                                    class="pop-menu-item"
                                    v-for="subItem in menuItem?.sub_navs || []"
                                    :key="subItem?.id"
                                    @click="changeMenu(subItem)"
                                >
                                    {{ subItem?.title }}
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="right-wrap">
                <!-- 更多导航 -->
                <div
                    class="option-wrap"
                    @mouseenter="changeWidth"
                    v-if="navList?.length && navList?.length > 6"
                >
                    <span class="option-wrap-more">更多</span>
                    <div
                        class="more-menu-list"
                        ref="menuRef"
                        :style="menuWidth"
                    >
                        <div
                            v-for="(item, index) in moreNavList"
                            :key="index"
                            class="mar-l40"
                        >
                            <div
                                class="pop-menu-header"
                                :class="{
                                    'pointer title-hover':
                                        !item.sub_navs ||
                                        item.sub_navs.length === 0
                                }"
                                @click="changeMenu(item, -1)"
                            >
                                {{ item.title }}
                            </div>
                            <ul v-if="item?.sub_navs?.length">
                                <li
                                    class="more-menu-item"
                                    v-for="(
                                        childrenItem, index
                                    ) in item.sub_navs"
                                    :key="index"
                                    @click="changeMenu(childrenItem, -1)"
                                >
                                    {{ childrenItem.title }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <!-- 工具导航 -->
                <div
                    class="tools-wrap"
                    v-if="toolNavList?.length && toolNavList[0]?.sub_navs"
                    :class="[
                        {
                            'mr-20':
                                toolNavList?.length &&
                                toolNavList[0]?.custom_name
                        }
                    ]"
                >
                    <div class="tools-title" v-if="toolNavList[0]?.custom_name">
                        {{ toolNavList[0].custom_name }}
                    </div>
                    <span v-else class="iconfont icon-a-fenlei2"></span>
                    <ul
                        class="submenu-list pop-menu-list"
                        :class="[
                            {
                                'tool-pop-menu-left':
                                    toolNavList?.length &&
                                    toolNavList[0]?.custom_name
                            }
                        ]"
                    >
                        <li
                            class="pop-menu-item"
                            v-for="subItem in toolNavList[0]?.sub_navs || []"
                            :key="subItem?.id"
                            @click="changeMenu(subItem)"
                        >
                            {{ subItem?.title }}
                        </li>
                    </ul>
                </div>
                <!-- 搜索内容 -->
                <!-- <el-input
                    ref="headerInputRef"
                    v-if="isSearch"
                    v-model.trim="searchVal"
                    placeholder="请输入搜索内容"
                    class="search-wrap">
                    <template #suffix>
                        <i class="iconfont icon-sousuo suffix-icon" />
                    </template>
                </el-input>
                <span v-else ref="headerSearchRef" class="search-wrap-icon" @click="isSearch = !isSearch">
                    <i class="iconfont icon-sousuo suffix-icon" />
                </span> -->
                <el-divider
                    class="middle-divider"
                    direction="vertical"
                ></el-divider>
                <template v-if="currentUser?.userId">
                    <div
                        class="news-img-wrap pointer"
                        @click="goSelfUrl('home.myMessage')"
                    >
                        <img
                            class="news-img"
                            src="~@/assets/img/gateway/news@2x.png"
                            alt=""
                        />
                        <div class="has-message" v-if="unreadMessageNum"> {{ unreadMessageNum }}  </div>
                    </div>
                    <HeaderDrop :applications="applications"></HeaderDrop>
                </template>
                <!-- 去登录 -->
                <template v-else>
                    <span class="login-btn pointer" @click="goLogin">{{
                        isRegist ? '登录/注册' : '登录'
                    }}</span>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref, computed, watch, onBeforeUnmount, onMounted} from 'vue';
import {useStore} from 'vuex';
import {useRoute} from 'vue-router';
import {pageJump} from '@/global/location-transfer';
import {getUrl} from '@/router/jumpHref.js';
import config from '@/global/config';
import {routeStatic} from '@/router/routes-static.js';
import HeaderDrop from './header-drop';

const store = useStore();
const route = useRoute();

const emit = defineEmits(['change-menu']);

const props = defineProps({
    menuList: {
        // 菜单
        type: Array,
        default: () => {
            return [];
        }
    },
    activeRoute: {
        type: Object,
        default: () => {
            return {};
        }
    }
});

const registMap = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let list =
        pagePermission['accountManage:loginAndRegist:isOpen']?.moduleRuleList ||
        [];
    let temp = {};
    list?.length &&
        list.forEach(element => {
            temp[element.ruleKey] = element.checked;
        });
    return temp;
});

const isRegist = computed(() => {
    return !registMap.value?.['0'];
});

// 获取当前用户信息
const currentUser = ref({});
const username = computed(() => {
    return currentUser.value?.realName || currentUser.value?.name || '';
});
// 监听个人信息变化
watch(
    () => store.state.currentUser,
    val => {
        currentUser.value = val;
        if (val.userId) {
            store.dispatch('user/getUnreadMessage');
            getApplicationList();
        }
    },
    {deep: true, immediate: true}
);

const unreadMessageNum = computed(() => {
    let num =
        store.state?.unreadMessage?.like + store.state?.unreadMessage?.message;
    if (+num == 0) {
        num = false;
    }
    if (+num > 99) {
        num = '99+';
    }
    return num;
});
// 搜索内容
const searchVal = ref('');

// 是否展开search
const isSearch = ref(false);

// 全部备案信息
const brand = computed(() => {
    // console.log('brand====', JSON.stringify(store.state.brand))
    return store.state.brand?.publishBrand || {};
});

// 具体备案信息
const brandInfo = computed(() => {
    // console.log('brandInfo====', JSON.stringify(brand.value?.brandConfig))
    return brand.value?.brandConfig || {};
});

// 当前选中的导航
const activeId = computed(() => {
    return props.activeRoute?.id || '';
});

// 前五个导航
const navList = computed(() => {
    console.log('navList====', props.menuList);
    let menuList = props.menuList?.length ? props.menuList : [];
    menuList = menuList.filter(item => item.moduleKey !== 'toolkit');
    return (menuList?.length && menuList.slice(0, 6)) || [];
});

// 更多导航
const moreNavList = computed(() => {
    let menuList = props.menuList?.length ? props.menuList : [];
    menuList = menuList.filter(item => item.moduleKey !== 'toolkit');
    return (menuList?.length && menuList) || [];
});

// 工具导航
const toolNavList = computed(() => {
    let menuList = props.menuList?.length ? props.menuList : [];
    menuList = menuList.filter(item => item.moduleKey === 'toolkit');
    return (menuList?.length && menuList) || [];
});

const menuRef = ref(null);

const menuWidth = ref({});

function changeWidth() {
    // 工具是文字 239
    // 工具是icon 181
    // 没有工具
    let navW = 0;
    if (toolNavList.value.length === 0) {
        navW = 1040;
    } else if (toolNavList.value[0]?.custom_name) {
        navW = 961;
    } else {
        navW = 1019;
    }
    if (menuRef.value?.clientWidth > navW) {
        menuWidth.value = {
            width: `${navW}px`,
            justifyContent: 'flex-end',
            flexWrap: 'wrap'
        };
    }
}

// 跳转路由
function changeMenu(menuItem) {
    emit('change-menu', menuItem);
}

function goLogin() {
    store.dispatch('logout');
}

function exit() {
    store.dispatch('logoutHome');
}

function goPage(name) {
    if (name === 'userHomePage' && !showPersonCenter.value) {
        return;
    }
    pageJump({name});
}

function goSelfUrl(str) {
    let url = getUrl(str);
    pageJump(url, '_blank');
}

const headerInputRef = ref(null);
const headerSearchRef = ref(null);

function mousedownChange(e) {
    let isInput =
        (headerInputRef.value && headerInputRef.value.ref.contains(e.target)) ||
        ''; // 是否包含搜索输入框
    let isIcon =
        (headerSearchRef.value && headerSearchRef.value.contains(e.target)) ||
        ''; // 是否包含搜索图标
    if (isInput || isIcon) {
        return;
    }
    isSearch.value = false;
}

const showManage = computed(() => {
    // 是否显示管理中心
    let pagePermission = store.state?.pagePermission || {};
    let isHaveIdmx = store.state.user?.isHaveIdmx;
    return !!pagePermission['manageCenter:base:home'] && isHaveIdmx;
});

const showPersonCenter = computed(() => {
    // 是否显示个人中心
    let pagePermission = store.state?.pagePermission || {};
    return !!pagePermission['personalCenter:page'];
});

const showStrain = computed(() => {
    // 是否显示培训管理系统
    let pagePermission = store.state?.pagePermission || {};
    let isHaveStrain = store.state.user?.isHaveStrain;
    return (
        !!pagePermission.continuingEducation &&
        !!pagePermission.train &&
        isHaveStrain
    );
});

const images = {
    'resourceApplication:my': require('@/assets/img/menu-icon/resource.png'),
    'coopgroup:my': require('@/assets/img/menu-icon/group.png'),
    'activity:my': require('@/assets/img/menu-icon/activity.png'),
    'train:my': require('@/assets/img/menu-icon/course.png'),
    'continuingEducation:my': require('@/assets/img/menu-icon/teach.png'),
    'video:my': require('@/assets/img/menu-icon/case.png'),
    'moocApplication:my': require('@/assets/img/menu-icon/mooc.png'),
    'material:my': require('@/assets/img/menu-icon/material.png')
};
const applications = ref([]);
// 获取应用
function getApplicationList() {
    G_transmit('getUserCenterLatestBrand', {
        name: 'getUserCenterLatestBrand'
    })
        .then(res => {
            const data = res?.data || [];
            let menuList = [];
            let tempMap = {};
            console.log('routeStatic', routeStatic);
            data.length &&
                data.forEach(item => {
                    if (
                        item.moduleKey &&
                        routeStatic[item.moduleKey] &&
                        routeStatic[item.moduleKey].name &&
                        !tempMap[item.moduleKey]
                    ) {
                        tempMap[item.moduleKey] = item;
                        let temp = {
                            path: routeStatic[item.moduleKey].path,
                            id: item.moduleKey,
                            title: routeStatic[item.moduleKey].title,
                            shortTitle: routeStatic[item.moduleKey].shortTitle,
                            route: {name: routeStatic[item.moduleKey].name},
                            isOther: false,
                            icon: images[item.moduleKey]
                        };
                        menuList.push(temp);
                    }
                });
            applications.value = menuList || [];
        })
        .catch(() => {});
}

onMounted(() => {
    window.addEventListener('mousedown', mousedownChange, true); // 监听鼠标点击事件
});

onBeforeUnmount(() => {
    window.removeEventListener('mousedown', mousedownChange, true);
});
</script>

<style lang="scss">
// .main-drop-menu {
//     .el-dropdown-menu__item {
//         justify-content: center;
//     }
// }
</style>

<style lang="scss" scoped>
// 主页导航主色
$nav-main-color: var(--nav-main-color);
// 主页导航选中主色
$nav-main-active-color: var(--nav-main-active-color);
// 主页更多下拉导航背景主色
$nav-main-sub-bg-more-color: var(--nav-main-sub-bg-more-color);
// 主页更多下拉导航文字主色
$nav-main-sub-color: var(--nav-main-sub-color);
// 主页更多下拉导航文字hover主色
$nav-main-sub-hover-color: var(--nav-main-sub-hover-color);

// 首页主色
$home-main-color: var(--home-main-color);

.header-container {
    width: 100%;
    height: 60px;
    color: var(--main-text-color);
    background-color: #ffffff;

    .login-btn {
        width: 94px;
        height: 32px;
        background: $home-main-color;
        border-radius: 4px;
        display: inline-block;
        color: #ffffff;
        line-height: 32px;
        text-align: center;
        font-size: 14px;
    }
    .menu-list {
        height: 100%;
    }
    .left-wrap {
        .logo {
            width: 26px;
            height: 26px;
        }
        .site-name {
            width: 98px;
            font-size: 14px;
            font-weight: bold;
            color: $nav-main-color;
            margin-left: 10px;
        }
        .little-site-name {
            font-size: 12px;
            line-height: 18px;
            text-align: center;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2; /* 这里是超出几行省略 */
            overflow: hidden;
        }
    }

    .menu-container {
        height: 60px;
        max-width: 700px;
        position: relative;
        .menu-item {
            font-size: 14px;
            margin-left: 40px;
            max-width: 228px;
            position: relative;
            height: 100%;
            &:hover {
                .pop-menu-list {
                    display: block;
                }
            }
        }
        .menu-item-name {
            max-width: 60px;
            text-align: center;
            color: $nav-main-color;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            &:hover {
                font-weight: bold;
            }
        }
        .menu-item-snv {
            &::after {
                content: '';
                background: url(~@/assets/img/login/head-down.png) no-repeat;
                width: 10px;
                height: 10px;
                background-size: contain;
                margin-left: 6px;
                display: inline-block;
                position: absolute;
                right: -16px;
                top: 50%;
                transform: translateY(-50%);
            }
        }
        .active {
            font-weight: bold;
            &::after {
                content: '';
                position: absolute;
                bottom: 8px;
                width: 24px;
                margin: 0 auto;
                height: 3px;
                background: $nav-main-active-color;
                border-radius: 2px;
                left: 50%;
                transform: translateX(-50%);
            }
        }
        .submenu-list {
            left: 30px;
            padding: 13px 20px;
        }
    }
    .option-wrap {
        position: relative;
        height: 100%;
        display: flex;
        align-items: center;

        &:hover {
            .more-menu-list {
                display: flex;
                white-space: nowrap;
            }
        }
    }
    .option-wrap-more {
        font-size: 14px;
        color: var(--color-light-black);
        position: relative;
        margin-right: 24px;
        cursor: pointer;

        &:hover {
            font-weight: bold;
        }
        &::after {
            content: '';
            background: url(~@/assets/img/login/head-down.png) no-repeat;
            width: 10px;
            height: 10px;
            background-size: contain;
            margin-left: 6px;
            display: inline-block;
        }
    }

    .more-menu-list,
    .pop-menu-list {
        position: absolute;
        background: $nav-main-sub-bg-more-color;
        backdrop-filter: blur(10px);
        z-index: 3000;
        top: 62px;
        transition: display 0.2s;
        display: none;
        box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.14);
        border-radius: 4px;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: -2px;
            width: 100%;
            height: 2px;
            background: transparent;
            display: block;
        }
    }
    .more-menu-list {
        min-width: 152px;
        right: 24px;
        padding: 10px 5px 0px;
        &.menu-width {
            width: 1040px;
            justify-content: flex-end;
            flex-wrap: wrap;
        }
    }
    .pop-menu-list {
        width: 130px;
        left: 50%;
        transform: translateX(-50%);
    }
    .pop-menu-item,
    .more-menu-item {
        color: $nav-main-sub-color;
        font-size: 14px;
        line-height: 22px;
        text-align: center;
        cursor: pointer;
        &:nth-child(n + 2) {
            margin: 12px 0 0;
        }
        &:hover {
            color: $nav-main-sub-hover-color;
        }
    }
    .more-menu-item {
        margin: 12px 0 0;
    }
    .pop-menu-header {
        font-size: 15px;
        font-weight: bold;
        color: var(--nav-main-sub-color);
        line-height: 24px;
    }
    .right-wrap {
        display: flex;
        align-items: center;
        height: 100%;
    }
    .search-wrap {
        width: 280px;
        background: #f8f8f8;
        border-radius: 18px;
        :deep(.el-input__wrapper) {
            border-radius: 18px;
            background: #f8f8f8;
            box-shadow: none;
            padding: 2px 16px;
        }
    }

    .search-wrap-icon {
        width: 42px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background: #f8f8f8;
        border-radius: 18px;
    }
    .suffix-icon {
        font-size: 18px;
        color: #000000;
        cursor: pointer;

        &:hover {
            color: $home-main-color;
        }
    }
    .news-img-wrap {
        position: relative;
        .has-message {
                position: absolute;
                right: -4px;
                top: -4px;
                width: 16px;
                height: 16px;
                border-radius: 50%;
                text-align: center;
                line-height: 16px;
                background: #ff4a4a;
                font-size: 10px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #ffffff;
                transform: scale(0.8);
            
        }
    }
    .news-img {
        width: 22px;
        height: 22px;
    }
    .user-img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
    }
    .user-name {
        margin-left: 6px;
        font-size: 14px;
        color: #000000;
    }
    .nav-item {
        display: flex;
        align-items: center;
        margin-left: 20px;
        &::after {
            content: '';
            background: url(~@/assets/img/login/head-down.png) no-repeat;
            width: 10px;
            height: 10px;
            background-size: contain;
            margin-left: 6px;
            display: inline-block;
        }
        &:focus {
            outline: none;
        }
    }
    .middle-divider {
        height: 12px;
        background-color: var(--color-light-gray);
        margin: 1px 20px;
    }
    .mar-l40 {
        padding: 10px 15px 20px 15px;
    }

    .title-hover {
        &:hover {
            color: $nav-main-sub-hover-color;
        }
    }
}
.tools-wrap {
    height: 60px;
    display: flex;
    align-items: center;
    // margin-left: 36px;
    position: relative;
    .iconfont {
        font-size: 22px;
        &:hover {
            color: $home-main-color;
        }
    }
    .tools-title {
        display: flex;
        align-items: center;
        font-size: 14px;
        line-height: 19px;
        color: var(--color-light-black);
        width: 60px;
        text-align: center;
        word-break: break-all;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        cursor: pointer;
        text-align: right;
        &:hover {
            font-weight: bold;
        }
        &::after {
            content: '';
            background: url(~@/assets/img/login/head-down.png) no-repeat;
            width: 10px;
            height: 10px;
            background-size: contain;
            margin-left: 6px;
            display: inline-block;
            position: absolute;
            right: -16px;
            top: 50%;
            transform: translateY(-50%);
        }
    }
    &:hover {
        .pop-menu-list {
            display: block;
        }
    }
    .submenu-list {
        padding: 16px 22px;
    }
    .pop-menu-list.tool-pop-menu-left {
        left: calc(50% + 8px);
    }
}

.mr-20 {
    margin-right: 20px;
}
</style>
